<?php


namespace App\Service;


use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class BaiduVoice
{
    // 百度语音接口：
    //   语音识别
    //   文字合成语音

    // 提交审核地址前缀
    protected $preUrl    = 'https://tsn.baidu.com/text2audio';
    protected $APIKey    = '6ubE97b1cgE2R8PPl9tgjYQx';
    protected $SecretKey = 'VCHQwoxcAsFwuUGhu47E2jkaKqUNH4hC';

    // 初始化操作
    public function __construct() { }

    // 短文本合成语音
    public function short($text)
    {
        $macSer = new GetMacAddress();
        $mac    = $macSer->getLinux();

        // per（基础音库） 度小宇=1，度小美=0，度逍遥（基础）=3，度丫丫=4
        //$text = iconv("UTF-8", "GBK", $text);
        $url  = 'https://tsn.baidu.com/text2audio';
        $data = ['tex' => urlencode($text), 'tok' => $this->getToken(), 'cuid' => 'fe80::216:3eff:fe14:8cb7', 'ctp' => 1, 'lan' => 'zh', 'per' => 0, 'spd' => 5, 'pit' => 5, 'vol' => 5, 'aue' => 3,];
        $res  = $this->request($url, $data);

        return $res;
    }

    // 长文本合成语音
    public function long()
    {

    }

    // 获取token 有效期为30天
    public function getToken()
    {
        // 是否有缓存
        $cookie_name  = 'baidu_voice_access_token';
        $access_token = Cache::get($cookie_name);
        if($access_token){
            return $access_token;
        }

        // 如果没有缓存 则会去百度获取
        //$AppID、$APIKey、$SecretKey
        $APIKey    = $this->APIKey;
        $SecretKey = $this->SecretKey;
        // 执行请求 获取 access_token
        $url  = "https://aip.baidubce.com/oauth/2.0/token?client_id=".$APIKey."&client_secret=".$SecretKey."&grant_type=client_credentials";
        $url  = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=".$APIKey."&client_secret=".$SecretKey;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json']);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 要求结果为字符串且输出到屏幕上

        $response = curl_exec($curl);
        curl_close($curl);

        // 不知道是不是需要只有处理
        $response = json_decode($response, true);
        // 是否成功
        $error = $response['error'] ?? '';
        if(empty($error)){
            $access_token = $response['access_token'] ?? '';
            $expires_in   = $response['expires_in'] ?? '';
            // 保存为缓存
            // 因为请求回来，需要花费时间，所以缓存时间应该比过期时间少一点
            Cache::add($cookie_name, $access_token, $expires_in - 20);

            return $access_token;
        }

        return $response;
    }

    // 请求操作
    protected function request($url = '', $param = '')
    {
        if(empty($url) || empty($param)){
            return false;
        }

        $paramsStr = http_build_query($param);
        $postUrl   = $url;
        //$postUrl   = $url.'?'.$paramsStr;

        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $paramsStr);

        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        // 保存为mp3文件
        if($param['aue'] == 3){
            $fileName = __DIR__.'/abc.mp3';
            file_put_contents($fileName, $data);
            // 上传参数
            $to        = 'baidu_voice/'.date('Y/Ym/d/').date('Ymd').microtime(true).mt_rand().'.mp3';
            $qiUpload  = new UploadManager();
            $accessKey = config('filesystems.disks.qiniu.access_key');
            $secretKey = config('filesystems.disks.qiniu.secret_key');
            $bucket    = config('filesystems.disks.qiniu.bucket');//上传空间名称
            // 上传
            $auth  = new Auth($accessKey, $secretKey);
            $token = $auth->uploadToken($bucket);
            $res   = $qiUpload->putFile($token, $to, $fileName, null, 'audio/mpeg', false);
            // 组合域名地址
            $domain = Config::get('site.cdnHost');
            if(substr($domain, -1) != '/'){
                $domain = $domain.'/';
            }
            $response = $domain.$to;
        } else{
            // 已达到打开api qps请求限制
            // Open api qps request limit reached
            $response = json_decode($data, true);
        }

        return $response;
    }

    protected function read_header($ch, $header)
    {
        global $g_has_error;

        $comps = explode(":", $header);
        // 正常返回的头部 Content-Type: audio/*
        // 有错误的如 Content-Type: application/json
        if(count($comps) >= 2){
            if(strcasecmp(trim($comps[0]), "Content-Type") == 0){
                if(strpos($comps[1], "audio/") > 0){
                    $g_has_error = false;
                } else{
                    echo $header." , has error \n";
                }
            }
        }

        return strlen($header);
    }

    // 结束程序
    // 抛出异常
    protected function throwIf($condition, $msg, $code = 400)
    {
        if($condition){
            throw new \RuntimeException($msg, $code);
        }
    }

}


